package com.ujn.zhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujn.zhxy.pojo.Admin;
import com.ujn.zhxy.pojo.LoginFrom;
import com.ujn.zhxy.pojo.Student;
import com.ujn.zhxy.pojo.Teacher;
import com.ujn.zhxy.service.AdminService;
import com.ujn.zhxy.service.StudentService;
import com.ujn.zhxy.service.TeacherService;
import com.ujn.zhxy.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController //注意 不是@Controller ，异步交互的方法
@RequestMapping("/sms/system")
@Api(tags = "系统控制器")
public class SystemController {
    //一些公共的功能

    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @ApiOperation("修改密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(
            @ApiParam("用户的token") @RequestHeader String token,
            @ApiParam("旧密码") @PathVariable("oldPwd") String oldPwd,
            @ApiParam("新密码") @PathVariable("newPwd") String newPwd
    ){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            //token过期
            return Result.fail().message("token失效，请 重新登陆后修改密码");
        }
        Integer userType = JwtHelper.getUserType(token);
        Long userId = JwtHelper.getUserId(token);

        oldPwd = MD5.encrypt(oldPwd);
        newPwd = MD5.encrypt(newPwd);
        switch (userType){
            case 1:
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("id",userId.intValue());
                queryWrapper.eq("password", oldPwd);
                Admin admin = adminService.getOne(queryWrapper);
                if (admin != null){
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
            case 2:
                QueryWrapper queryWrapper2 = new QueryWrapper();
                queryWrapper2.eq("id",userId.intValue());
                queryWrapper2.eq("password", oldPwd);
                Student student = studentService.getOne(queryWrapper2);
                if (student != null){
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
            case 3:
                QueryWrapper queryWrapper3 = new QueryWrapper();
                queryWrapper3.eq("id",userId.intValue());
                queryWrapper3.eq("password", oldPwd);
                Teacher teacher = teacherService.getOne(queryWrapper3);
                if (teacher != null){
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
        }

        return Result.ok();
    }


    @ApiOperation(("头像上传入口"))
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @ApiParam("要上传的文件") @RequestPart("multipartFile") MultipartFile multipartFile,
            HttpServletRequest request
    ){
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFileName = uuid + originalFilename.substring(i);
        //保存文件
        //将文件发送到第三方 或 独立的图片服务器上，
        String portraitPath = "D:\\work\\zhxy\\target\\classes\\public\\upload/" + newFileName;
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //响应图片的路径

        String path = "upload/" + newFileName;
        return Result.ok(path);
    }

    @ApiOperation("通过token请求信息")
    @GetMapping("/getInfo")
    public Result getInfoByToken(
            @ApiParam("发送的token") @RequestHeader("token") String token){

        //先验证一下token有没有过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        // 从token中解析出 用户id和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        Map<String,Object> map = new LinkedHashMap<>();
        switch (userType){
            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
                Student student = studentService.getStudentById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher = teacherService.getTeacherById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;
        }

        return Result.ok(map);

    }

    @ApiOperation("登陆请求")
    @PostMapping("/login")
    public Result login(
            @ApiParam("登陆时上传的json") @RequestBody LoginFrom loginFrom,
            @ApiParam("HttpServletRequest") HttpServletRequest request){
        // 验证码校验
        HttpSession session = request.getSession();
        String sessionVerifiCode = (String) session.getAttribute("verifiCode"); // 在获取验证码时放入session的正确的验证码
        String loginVerifiCode = loginFrom.getVerifiCode(); // 用户输入的验证码
        if("".equals(sessionVerifiCode) || null == sessionVerifiCode){
            return Result.fail().message("验证码失效，请刷新后重试");
        }
        if(!sessionVerifiCode.equalsIgnoreCase(loginVerifiCode)){
            return Result.fail().message("验证码有误，请小心输入后重试");
        }
        // 从session域中移除现有验证码
        session.removeAttribute("verifiCode");
        // 分用户类型校验

        //准备一个map，用于存放响应的数据
        Map<String,Object> map = new LinkedHashMap<>();
        switch (loginFrom.getUserType()){
            case 1:
                Admin admin = adminService.login(loginFrom);
                try {
                    if(null != admin){
                        // 用户类型和用户id转换为一个密文，以token的名称向客户端反馈
                        String token = JwtHelper.createToken(admin.getId().longValue(), 1);
                        map.put("token",token);
                    }else {
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                Student student = studentService.login(loginFrom);
                try {
                    if(null != student){
                        // 用户类型和用户id转换为一个密文，以token的名称向客户端反馈
                        String token = JwtHelper.createToken(student.getId().longValue(), 2);
                        map.put("token",token);
                    }else {
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 3:
                Teacher teacher = teacherService.login(loginFrom);
                try {
                    if(null != teacher){
                        // 用户类型和用户id转换为一个密文，以token的名称向客户端反馈
                        String token = JwtHelper.createToken(teacher.getId().longValue(), 3);
                        map.put("token",token);
                    }else {
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        return Result.fail().message("查无此用户");
        //
    }

    @ApiOperation("请求验证码图片")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        //获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        // 获取图片上的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        //将验证码文本放入session ，为下一次响应做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        try {
            // 将验证码图片相应给浏览器
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
